package com.baijia.tianxiao.connect.common.auth;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.baijia.tianxiao.connect.common.util.ConnectUtil;
import com.baijia.tianxiao.connect.common.util.HttpCommonUtil;
import com.baijia.tianxiao.connect.common.util.InnerAuthToken;

public class InnerTokenUtil {
	private static Logger logger = LoggerFactory.getLogger(InnerTokenUtil.class);
	
	public static boolean checkInnerIpOrToken(HttpServletRequest request) {
		// 内网访问通过
		String clientIp = HttpCommonUtil.getRemoteIp(request);
		boolean bool = HttpCommonUtil.isInnerIP(clientIp);
		if (!bool) {
			// 如果是不是内网，验证token，等于是后门
			bool = InnerTokenUtil.checkToken(request);
		}
		return bool;
	}
	public static boolean checkToken(HttpServletRequest request){
		String token = (String)request.getParameter("token");
		if(StringUtils.isBlank(token)){
			return false;
		}
		InnerAuthToken authToken = null;
		try {
			String jsonStr = ConnectUtil.getBizNameByToken(token);
			authToken = JSON.parseObject(jsonStr, InnerAuthToken.class);
		} catch (Exception e) {
			logger.error("TianxiaoWebNormalInterceptor check error",e);
			return false;
		}
		if(authToken !=null ){
			if(checkTime(authToken.getTime(),10) && checkDomain(authToken.getDomain()) && checkUser(authToken.getUserType())){
				return true;
			}
		}
		return false;
		
	}
	
	private static boolean checkDomain(String domain){
		String defaultDomain = "inner";
		if(StringUtils.equals(defaultDomain, domain)){
			return true;
		}
		return false;
	}
	private static boolean checkUser(String user){
		String defaultUser = "tianxiao";
		if(StringUtils.equals(defaultUser, user)){
			return true;
		}
		return false;
	}
	
	public static boolean checkTime(Long time,int expireMin){
		
		if(time == null){
			return false;
		}
		long expire = System.currentTimeMillis() - time;
		if(expire<expireMin*60*1000){
			return true;
		}
		return false;
	}
}
